#include <QDebug>

#include "xmlparser.h"
#include "messagedisplay.h"

XmlParser::XmlParser(const QString &fileName):
        m_file(fileName)
{
    /* Ensure that the file was successfully loaded. */
    if(!m_file.open(QIODevice::ReadOnly | QIODevice::Text))
        (new MessageDisplay("There was an error loading the file",
                           "Parser File Error"))->show();
}

void XmlParser::loadObject(const QString &object) {

    /* Pad the object name with an XML start tag and then move to it in the
     * file.
     */
    QString opener = "<" + object + ">";
    this->moveToTag(opener);

}

void XmlParser::closeObject(const QString &object) {

    /* Pad the object name with an XML close tag and then move to it in the
     * file.
     */
    QString closer = "</" + object + ">";
    this->moveToTag(closer);

}

QString XmlParser::loadAttribute(const QString &attribute) {

    /* Pad the object name with an XML start tag and then move to it in the
     * file.
     */
    QString attTag = "<" + attribute + ">";
    QString buffer = this->moveToTag(attTag);

    /* Section off the buffer so that it only contains the data between the
     * XML tags, so the string is only the data that line between the <>'s
     */
    buffer = buffer.section(attribute, 1, 1);
    buffer.remove(0, 1).truncate(buffer.size() - 3);

    return buffer;
}

QString XmlParser::moveToTag(const QString &tag) {

    /* Make a buffer that can survive throughout the function */
    QString buffer;

    /* Keep parsing lines until the correct tag is located */
    do {
        if(m_file.atEnd()) {
            QString message("There was an error reading the file.\n");
            message.append("Could not find the term: ");
            message.append(tag);
            (new MessageDisplay(message , "Read Error"))->show();
            return "";
        }
        buffer = m_file.readLine();
    } while (!buffer.contains(tag));

    /* Return the entire line on which that tag is located. */
    return buffer;
}

void XmlParser::ignoreNextLine() {

    qDebug() << m_file.readLine();
}
